package com.itmk.login.controller;

import com.alibaba.fastjson.JSONObject;
import com.itmk.colloge.service.CollogeService;
import com.itmk.colloge.service.impl.CollogeServiceImpl;
import com.itmk.login.entity.ResultTotal;
import com.itmk.major.entity.MajorResult;
import com.itmk.major.service.MajorService;
import com.itmk.major.service.impl.MajorServiceImpl;
import com.itmk.student.entity.Student;
import com.itmk.student.service.StudentService;
import com.itmk.student.service.impl.StudentServiceImpl;
import com.itmk.teacher.entity.Teacher;
import com.itmk.teacher.service.TeacherService;
import com.itmk.teacher.service.impl.TeacherServiceImpl;
import com.itmk.user.entity.SysUser;
import com.itmk.user.service.SysUserService;
import com.itmk.user.service.impl.SysUserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 处理登录模块的请求，登录控制器
 */
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
    private StudentService studentService = new StudentServiceImpl();
    private TeacherService teacherService = new TeacherServiceImpl();
    private SysUserService sysUserService = new SysUserServiceImpl();
    private MajorService majorService = new MajorServiceImpl();
    private CollogeService collogeService = new CollogeServiceImpl();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method.equals("login")) {
            login(req, resp);
        } else if (method.equals("adminHomeUI")) {
            adminHomeUI(req, resp);
        } else if (method.equals("adminWelcome")) {
            adminWelcome(req, resp);
        } else if (method.equals("loginOut")) {
            loginOut(req, resp);
        } else if (method.equals("studentWelcome")) {
            studentWelcome(req, resp);
        } else if (method.equals("teacherWelcome")) {
            teacherWelcome(req, resp);
        } else if (method.equals("getCount")) {
            getCount(req, resp);
        } else if (method.equals("getMajorTotal")) {
            getMajorTotal(req, resp);
        }

    }

    private void getMajorTotal(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        MajorResult majorResult = majorService.majorCount();
        JSONObject object = new JSONObject();
        object.put("code", 200);//返回成功的状态码 200
        object.put("data", majorResult);
        //把数据写回前端
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        writer.print(object.toJSONString());
    }

    private void getCount(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int teachertotal = teacherService.getTotal();
        int stutotal = studentService.getTotal();
        int mjtotal = majorService.getTotal();
        int collogetotal = collogeService.getTotal();
        //返回前端
        ResultTotal total = new ResultTotal();
        total.setCollogetotal(collogetotal);
        total.setMjtotal(mjtotal);
        total.setStutotal(stutotal);
        total.setTeachertotal(teachertotal);
        JSONObject object = new JSONObject();
        object.put("code", 200);//返回成功的状态码 200
        object.put("data", total);
        //把数据写回前端
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        writer.print(object.toJSONString());
    }

    private void loginOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("WEB-INF/jsp/login.jsp").forward(req, resp);
    }

    /**
     * 登录 ： 通过JSON传输数据，返回JSON数据
     *
     * @param req
     * @param resp
     */
    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //设置请求头，返回JSON数据
        resp.setContentType("application/json;charset=UTF-8");

        //验证码验证： 把前端传递过来的验证码 和 session里面的做对比，
        //从session里面获取验证码
        HttpSession session = req.getSession();
        String sessionCode = (String) session.getAttribute("code");
        //获取前端传递过来的验证码
        String code = req.getParameter("code");
        if (!sessionCode.equals(code)) {
            //构造返回的数据格式
            JSONObject object = new JSONObject();
            object.put("code", 600);//返回成功的状态码 200
            object.put("msg", "验证码输入错误!");
            //把数据写回前端
            PrintWriter writer = resp.getWriter();
            writer.print(object.toJSONString());
        } else {
            //查询数据库
            String userType = req.getParameter("userType");
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            if (userType.equals("1")) { //学生
                Student student = studentService.login(username, password);
                if (student == null) {
                    //构造返回的数据格式
                    JSONObject object = new JSONObject();
                    object.put("code", 700);//返回成功的状态码 200
                    object.put("msg", "用户名或者密码!");
                    //把数据写回前端
                    PrintWriter writer = resp.getWriter();
                    writer.print(object.toJSONString());
                } else {
                    //把登录的用户存放到session
                    session.setAttribute("user", student);
                    session.setAttribute("username", student.getStuName());
                    session.setAttribute("userId", student.getStuId());
                    //构造返回的数据格式
                    JSONObject object = new JSONObject();
                    object.put("code", 200);//返回成功的状态码 200
                    object.put("msg", "登录成功!");
                    //把数据写回前端
                    PrintWriter writer = resp.getWriter();
                    writer.print(object.toJSONString());
                }
            } else if (userType.equals("2")) { //教师
                Teacher teacher = teacherService.login(username, password);
                if (teacher == null) {
                    //构造返回的数据格式
                    JSONObject object = new JSONObject();
                    object.put("code", 700);//返回成功的状态码 200
                    object.put("msg", "用户名或者密码!");
                    //把数据写回前端
                    PrintWriter writer = resp.getWriter();
                    writer.print(object.toJSONString());
                } else {
                    //把登录的用户存放到session
                    session.setAttribute("user", teacher);
                    session.setAttribute("userId", teacher.getTeacherId());
                    session.setAttribute("username", teacher.getTeacherName());
                    //构造返回的数据格式
                    JSONObject object = new JSONObject();
                    object.put("code", 200);//返回成功的状态码 200
                    object.put("msg", "登录成功!");
                    //把数据写回前端
                    PrintWriter writer = resp.getWriter();
                    writer.print(object.toJSONString());
                }
            } else { //管理员
                SysUser sysUser = sysUserService.login(username, password);
                if (sysUser == null) {
                    //构造返回的数据格式
                    JSONObject object = new JSONObject();
                    object.put("code", 700);//返回成功的状态码 200
                    object.put("msg", "用户名或者密码!");
                    //把数据写回前端
                    PrintWriter writer = resp.getWriter();
                    writer.print(object.toJSONString());
                } else {
                    //把登录的用户存放到session
                    session.setAttribute("user", sysUser);
                    session.setAttribute("userId", sysUser.getUserId());
                    session.setAttribute("username", sysUser.getUsername());
                    //构造返回的数据格式
                    JSONObject object = new JSONObject();
                    object.put("code", 200);//返回成功的状态码 200
                    object.put("msg", "登录成功!");
                    //把数据写回前端
                    PrintWriter writer = resp.getWriter();
                    writer.print(object.toJSONString());
                }
            }
            session.setAttribute("userType", userType);
        }
    }

    /**
     * 返回首页页面
     */
    public void adminHomeUI(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userType = req.getParameter("userType");
        //不同的用户，跳转到不同的首页
        if (userType.equals("1")) {
            req.getRequestDispatcher("WEB-INF/jsp/student/student_home.jsp").forward(req, resp);
        } else if (userType.equals("2")) {
            req.getRequestDispatcher("WEB-INF/jsp/teacher/teacher_home.jsp").forward(req, resp);
        } else if (userType.equals("3")) {
            req.getRequestDispatcher("WEB-INF/jsp/home/admin_home.jsp").forward(req, resp);
        }
    }

    /**
     * 返回管理员欢迎页面
     */
    public void adminWelcome(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.getRequestDispatcher("WEB-INF/jsp/home/admin_welcome.jsp").forward(req, resp);
    }

    /**
     * 返回管学生欢迎页面
     */
    public void studentWelcome(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("WEB-INF/jsp/student/student_welcome.jsp").forward(req, resp);
    }

    /**
     * 返回教师欢迎页面
     */
    public void teacherWelcome(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("WEB-INF/jsp/teacher/teacher_welcome.jsp").forward(req, resp);
    }
}
